#import "NSBrowser+SRAdditions.h"
#import "NSIndexPath+SRAdditions.h"

@interface NSBrowser (SRAdditionsPrivate)
-(NSIndexPath *)indexPathForItem_:(id)item startingAtItem:(id)startingItem;
@end

@implementation NSBrowser (SRAdditions)

-(NSArray *)selectedItems {
    NSArray *selectedIndexPaths = [self selectionIndexPaths];
    NSMutableArray *selectedItems = [NSMutableArray arrayWithCapacity:[selectedIndexPaths count]];
    for (NSIndexPath *indexPath in selectedIndexPaths) {
        [selectedItems addObject:[self itemAtIndexPath:indexPath]];
    }
    return selectedItems;
}

-(NSIndexPath *)indexPathForItem:(id)item {
    NSAssert([self delegate] && [[self delegate] respondsToSelector:@selector(browser:numberOfChildrenOfItem:)], ([NSString stringWithFormat:@"Invalid delegate %@.  Must implement item delegate methods to use indexPathForItem", [self delegate]]));
    return [self indexPathForItem_:item startingAtItem:nil];
}

-(NSIndexPath *)indexPathForItem_:(id)item startingAtItem:(id)startingItem {
    NSInteger itemChildCount = [[self delegate] browser:self numberOfChildrenOfItem:startingItem];
    for (NSInteger currentChild = 0; currentChild < itemChildCount; currentChild++) {
        id child = [[self delegate] browser:self child:currentChild ofItem:startingItem];
        if (child == item) 
            return [NSIndexPath indexPathWithIndex:currentChild];
        NSIndexPath *childIndexPath = [self indexPathForItem_:item startingAtItem:child];
        if (childIndexPath)
            return [childIndexPath indexPathByAddingLeadingIndex:currentChild];
    }
    return nil;
}

-(BOOL)selectItem:(id)item {
    NSIndexPath *itemIndexPath = [self indexPathForItem:item];
    if (!itemIndexPath)
        return NO;
    [self setSelectionIndexPath:itemIndexPath];
    return YES;
}

@end
